'use strict';

const db = uniCloud.database();

exports.main = async (event, context) => {
  console.log('【submitEvaluation】云函数被调用，event：', event);
  
  const { taskId, rating, content, userId } = event;
  
  if (!taskId || !rating || !userId) {
    return {
      code: 400,
      msg: '缺少必要参数',
      data: null
    };
  }
  
  try {
    // 1. 先获取任务信息，确认接单者ID
    const taskResult = await db.collection('taskList').doc(taskId).get();
    if (!taskResult.data || taskResult.data.length === 0) {
      return {
        code: 404,
        msg: '任务不存在',
        data: null
      };
    }
    
    const task = taskResult.data[0];
    const receiverId = task.receiver_id; // 接单者ID
    
    console.log('【submitEvaluation】任务信息：', task);
    console.log('【submitEvaluation】接单者ID：', receiverId);
    
    if (!receiverId) {
      return {
        code: 400,
        msg: '任务未找到接单者',
        data: null
      };
    }
    
    // 2. 更新任务评价信息并完成任务
    const updateResult = await db.collection('taskList').doc(taskId).update({
      evaluation: {
        rating: rating,
        content: content || '',
        evaluator_id: userId,
        evaluate_time: new Date()
      },
      evaluated: true,
      status: 'completed', // 评价完成后任务状态变为已完成
      complete_time: new Date().toISOString() // 记录完成时间
    });
    
    console.log('【submitEvaluation】任务评价更新结果：', updateResult);
    
    if (updateResult.updated > 0) {
      // 3. 结算任务收入给接单者
      try {
        console.log('【submitEvaluation】开始结算任务收入:', {
          taskId,
          receiverId,
          status: 'completed'
        });
        
        const incomeResult = await uniCloud.callFunction({
          name: 'updateTaskIncome',
          data: {
            taskId: taskId,
            receiverId: receiverId,
            status: 'completed'
          }
        });
        
        console.log('【submitEvaluation】任务收入结算结果:', incomeResult);
        
        if (incomeResult.result && incomeResult.result.code === 200) {
          console.log('【submitEvaluation】任务收入结算成功');
        } else {
          console.error('【submitEvaluation】任务收入结算失败:', incomeResult.result);
        }
      } catch (incomeError) {
        console.error('【submitEvaluation】收入结算异常:', incomeError);
        // 收入结算失败不影响评价提交成功
      }
      
      // 4. 给接单者加积分
      try {
        // 根据评价星级计算积分（1-5星对应10-50积分）
        const pointsToAdd = rating * 10;
        
        // 调用积分管理云函数给接单者加积分
        const scoreResult = await uniCloud.callFunction({
          name: 'scoreManager',
          data: {
            action: 'task_evaluation_reward',
            userId: receiverId,
            data: {
              taskId: taskId,
              taskTitle: task.title || task.type,
              rating: rating,
              evaluatorId: userId,
              score: pointsToAdd
            }
          }
        });
        
        console.log('【submitEvaluation】积分奖励结果：', scoreResult);
        
        // 4. 发送通知给接单者
        try {
          // 获取评价者信息
          const evaluatorResult = await db.collection('uni-id-users').doc(userId).get();
          const evaluatorName = evaluatorResult.data && evaluatorResult.data.length > 0 
            ? (evaluatorResult.data[0].nickname || evaluatorResult.data[0].username || '用户')
            : '用户';
          
          console.log('【submitEvaluation】评价者信息：', evaluatorResult.data);
          console.log('【submitEvaluation】评价者昵称：', evaluatorName);
          
          // 发送任务完成和评价奖励通知
          const notificationResult = await uniCloud.callFunction({
            name: 'createNotification',
            data: {
              userId: receiverId,
              type: 'task_status',
              category: 'task',
              title: '任务完成并获得奖励',
              content: `恭喜！您完成的任务"${task.title || task.type}"已通过验收，获得${rating}星评价，获得${pointsToAdd}积分奖励！任务收入已结算到您的钱包。${content ? '\n评价内容：' + content : ''}`,
              relatedId: taskId,
              relatedType: 'task',
              priority: 'normal',
              actionUrl: '/pages/user/Wallet/Wallet',
              actionText: '查看钱包'
            }
          });
          
          console.log('【submitEvaluation】通知创建结果：', notificationResult);
          
          if (notificationResult.result && notificationResult.result.success) {
            console.log('【submitEvaluation】通知发送成功');
          } else {
            console.error('【submitEvaluation】通知创建失败:', notificationResult.result);
          }
        } catch (notificationError) {
          console.error('【submitEvaluation】通知发送失败:', notificationError);
          // 通知发送失败不影响评价提交成功
        }
        
      } catch (pointsError) {
        console.error('【submitEvaluation】积分奖励失败:', pointsError);
        // 积分奖励失败不影响评价提交成功
      }
      
      return {
        code: 200,
        msg: '评价提交成功，任务已完成，接单者已获得积分奖励和收入结算',
        data: {
          taskId: taskId,
          rating: rating,
          content: content,
          evaluateTime: new Date(),
          pointsAwarded: rating * 10,
          receiverId: receiverId,
          taskCompleted: true,
          incomeSettled: true
        }
      };
    } else {
      return {
        code: 404,
        msg: '任务不存在或更新失败',
        data: null
      };
    }
    
  } catch (error) {
    console.error('【submitEvaluation】异常:', error);
    return {
      code: 500,
      msg: '提交评价失败：' + error.message,
      data: null
    };
  }
};